/*
 * Copyright (C) 2013 Daniel Wasilew <daniel.wasilew@codeminer.org>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.codeminer.parts.database.dao;

import org.codeminer.database.DatabaseConnection;
import org.codeminer.database.DatabaseException;
import org.codeminer.parts.database.sql.From;
import org.codeminer.parts.database.sql.SQL;
import org.codeminer.parts.library.Album;
import org.codeminer.parts.library.Artist;
import org.codeminer.parts.library.Song;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

/**
 *
 * @author Daniel Wasilew <daniel.wasilew@codeminer.org>
 */
public final class AlbumDAO extends DAO {

    private AlbumDAO() {
    }

    public static long store(Album album, DatabaseConnection connection) throws DatabaseException {
        connection.accuireWriteLock();
        try {
            updateAndGetNextId(connection, album);
            String insert = SQL.insertInto("Albums").values().value(album.getOid()).value(album.getYear()).value(album.getTitle()).value(album.getCddb()).toSQL();
            executeInsert(connection, insert);
            return album.getOid();
        } finally {
            connection.releaseWriteLock();
        }
    }

    public static List<Album> get(Artist searchCriteria, DatabaseConnection connection) throws DatabaseException {
        connection.accuireReadLock();
        try {
            String albumOIDQuery = SQL.select("Album_Id").from("ALBUMS_FOR_ARTISTS").where("Artist_Id").is(searchCriteria.getOid()).toSQL();
            List<Long> albumIds = queryIds(albumOIDQuery, "Album_Id", connection);
            List<Album> results = new LinkedList<>();
            for (Long albumId : albumIds) {
                results.addAll(get(Album.byOId(albumId), connection));
            }
            return results;
        } finally {
            connection.releaseReadLock();
        }
    }

    public static List<Album> get(Album searchCriteria, DatabaseConnection connection) throws DatabaseException {
        ResultSet resultSet = null;
        connection.accuireReadLock();
        try {
            String query = null;
            From select = SQL.select().from("Albums");
            if (searchCriteria == null) {
                query = select.toSQL();
            } else if (searchCriteria.getOid() != -1) { //search by oid
                query = select.where("Album_Id").is(searchCriteria.getOid()).toSQL();
            } else if (searchCriteria.getTitle() != null) { //search by title
                query = select.where("Title").is(searchCriteria.getTitle()).toSQL();
            } else if (searchCriteria.getCddb() != null) { //search by CDDB
                query = select.where("CDDB").is(searchCriteria.getCddb()).toSQL();
            } else if (searchCriteria.getYear() != -1) { //search by Year
                query = select.where("Album_Year").is(searchCriteria.getYear()).toSQL();
            }
            resultSet = connection.createStatement().executeQuery(query);
            List<Album> result = new LinkedList<>();
            while (resultSet.next()) {
                long oid = resultSet.getLong("Album_Id");
                int year = resultSet.getInt("Album_Year");
                String title = resultSet.getString("Title");
                String cddb = resultSet.getString("CDDB");
                final Album album = new Album(year, title, cddb);
                album.setOid(oid);
                result.add(album);
            }
            return result;
        } catch (SQLException ex) {
            throw new DatabaseException(ex);
        } finally {
            connection.releaseReadLock();
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException ignored) {
                }
            }
        }
    }

    public static void addAlbumToArtist(Album album, Artist artist, DatabaseConnection connection) throws DatabaseException {
        validateIdentifiables(artist, artist);

        List<Album> currentAlbums = get(artist, connection);
        if (currentAlbums.contains(album)) {
            return;
        }

        String insert = SQL.insertInto("ALBUMS_FOR_ARTISTS").values().value(artist.getOid()).value(album.getOid()).toSQL();
        connection.accuireWriteLock();
        try {
            executeInsert(connection, insert);
        } finally {
            connection.releaseWriteLock();
        }
    }

    public static void addSongToAlbum(Song song, Album album, DatabaseConnection connection) throws DatabaseException {
        validateIdentifiables(album, song);

        String insert = SQL.insertInto("SONGS_FOR_ALBUM").values().value(album.getOid()).value(song.getOid()).toSQL();
        connection.accuireWriteLock();
        try {
            executeInsert(connection, insert);
        } finally {
            connection.releaseWriteLock();
        }
    }

    public static boolean delete(Album album, DatabaseConnection connection) throws DatabaseException {
        validateIdentifiable(album);
        connection.accuireWriteLock();
        try {
            String deleteStatement = SQL.delete().from("Albums").where("Album_Id").is(album.getOid()).toSQL();
            return executeUpdate(connection, deleteStatement);
        } finally {
            connection.releaseWriteLock();
        }
    }

    public static boolean update(Album album, DatabaseConnection connection) throws DatabaseException {
        validateIdentifiable(album);
        connection.accuireWriteLock();
        try {
            String query = SQL.update("Albums").
                    set("Album_Year", album.getYear()).
                    set("Title", album.getTitle()).
                    set("CDDB", album.getCddb()).
                    where("Album_Id").is(album.getOid()).toSQL();
            return executeUpdate(connection, query);
        } finally {
            connection.releaseWriteLock();
        }
    }
}
